package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func main() {
	file, _ := ioutil.ReadFile("talk.json")

	qs := []Group{}

	err := json.Unmarshal(file, &qs)
	if err != nil {
		panic(err)
	}
	f := "questions.txt"
	fileHandle, err := os.OpenFile(f, os.O_RDONLY|os.O_CREATE, 0666)
	defer fileHandle.Close()
	writer := bufio.NewWriter(fileHandle)

	WriteFile(writer, qs)
	writer.Flush()

	if err != nil {
		panic(err)
	}
}

func WriteFile(buf *bufio.Writer, qs []Group) {
	for i, q := range qs {
		f := q.Payload.Field
		buf.WriteString(fmt.Sprintf("第 %d 章 %s \r\n", i+1, f.Fname))
		sf := q.Payload.SubField

		for j, s := range sf {
			buf.WriteString(fmt.Sprintf("第 %d.%d 节 %s \r\n", i+1, j+1, s.Field.Fname))
			buf.WriteString("\r\n")
			for _, k := range s.Skill {
				buf.WriteString(fmt.Sprintf("[%s] %s\r\n", k.Code, k.Title))
				buf.WriteString(fmt.Sprintf("%s \r\n", strings.ReplaceAll(k.Skilldescribe, "\r\n", "")))

				for _, a := range k.Answers {
					buf.WriteString(fmt.Sprintf("\t %s 分 %s ", a.Options, a.Describe))
				}
				buf.WriteString("\r\n\r\n")
			}
		}
	}
}

type Group struct {
	Status  int32   `json:"status"`
	Message string  `json:"message"`
	Payload Payload `json:"payload"`
}

type Payload struct {
	Field    Field      `json:"field"`
	SubField []SubField `json:"subfield"`
}

type Field struct {
	Fid         int         `json:"fid"`
	Ancestorsid int         `json:"ancestorsid"`
	Parentid    int         `json:"parentid"`
	Fname       string      `json:"fname"`
	Status      int         `json:"status"`
	Isdel       int         `json:"isdel"`
	Uniacid     int         `json:"uniacid"`
	CreatedAt   interface{} `json:"created_at"`
	UpdatedAt   interface{} `json:"updated_at"`
	DeletedAt   interface{} `json:"deleted_at"`
	Depth       int         `json:"depth"`
	Sequence    string      `json:"sequence"`
}

type SubField struct {
	Parentid int     `json:"parentid"`
	Field    Field   `json:"field"`
	Skill    []Skill `json:"skill"`
}

type Skill struct {
	Id            int      `json:"id"`
	Pf            int      `json:"pf"`
	Title         string   `json:"title"`
	Code          string   `json:"code"`
	Skilldescribe string   `json:"skilldescribe"`
	Itemsid       int      `json:"itemsid"`
	Answers       []Answer `json:"answers"`
	Checkanswer   string   `json:"checkanswer"`
}

type Answer struct {
	Options  string `json:"options"`
	Describe string `json:"describe"`
}
